package com.song.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSONObject;
import com.song.common.constant.RedisConstants;
import com.song.common.handler.sentinel.SentinelBlockHandler;
import com.song.common.handler.sentinel.SentinelExceptionHandler;
import com.song.common.util.JwtUtil;
import com.song.user.feign.OrderService;
import com.song.user.util.RedisUtil;
import com.song.user.view.param.LoginParam;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.GetMapping;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.song.user.entity.User;
import com.song.user.service.UserService;
import com.song.common.result.ResultEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.Serializable;
import java.util.Optional;

/**
* <p>
    * 用户信息 控制器
    * </p>
*
* @author song
* @since 2023-11-02
*/
@Api(tags = {"用户信息 控制器"})
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private OrderService orderService;

    /**
    * 分页查询数据
    *
    * @author song
    * @Date 2023-11-02
    */
    @ApiOperation(value = "按条件分页检索用户信息",notes = "按条件分页检索用户信息")
    @GetMapping(value = "/pageList")
    public ResultEntity<Page<User>> pageList(
        @Validated User user,
        @ApiParam(value = "页码", defaultValue = "1")
        @RequestParam(defaultValue = "1") int pageNum,
        @ApiParam(value = "分页大小", defaultValue = "10")
        @RequestParam(defaultValue = "10") int pageSize
    ) {
        Page<User> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        if(ObjectUtils.isNotEmpty(user.getId())){
            lambda.eq(User::getId,user.getId());
        }
        if(ObjectUtils.isNotEmpty(user.getName())){
            lambda.eq(User::getName,user.getName());
        }
        if(ObjectUtils.isNotEmpty(user.getIdCard())){
            lambda.eq(User::getIdCard,user.getIdCard());
        }
        if(ObjectUtils.isNotEmpty(user.getUsername())){
            lambda.eq(User::getUsername,user.getUsername());
        }
        if(ObjectUtils.isNotEmpty(user.getPassword())){
            lambda.eq(User::getPassword,user.getPassword());
        }
        if(ObjectUtils.isNotEmpty(user.getStatus())){
            lambda.eq(User::getStatus,user.getStatus());
        }
        if(ObjectUtils.isNotEmpty(user.getCreateTime())){
            lambda.eq(User::getCreateTime,user.getCreateTime());
        }
        if(ObjectUtils.isNotEmpty(user.getUpdateTime())){
            lambda.eq(User::getUpdateTime,user.getUpdateTime());
        }
        return ResultEntity.success(userService.page(page,lambda));
    }

    /**
    * 查询数据List
    *
    * @author song
    * @Date 2023-11-02
    */
    @ApiOperation(value = "查询全部用户信息",notes = "查询全部用户信息")
    @GetMapping(value = "/list")
    public ResultEntity<List<User>> list() {
        List<User> userList = userService.list();
        return ResultEntity.success(userList);
    }

    /**
    * 用户信息新增
    *
    * @author song
    * @Date 2023-11-02
    */
    @ApiOperation(value = "新增用户信息",notes = "新增用户信息")
    @PostMapping(value = "/add")
    public ResultEntity add(@RequestBody User user) {
        userService.save(user);
        return ResultEntity.success();
    }

    /**
    * 用户信息修改
    *
    * @author song
    * @Date 2023-11-02
    */
    @ApiOperation(value = "修改用户信息",notes = "修改用户信息")
    @PostMapping(value = "/update")
    public ResultEntity edit(@RequestBody User user) {
        userService.updateById(user);
        return ResultEntity.success();
    }

    /**
    * 删除用户信息
    *
    * @author song
    * @Date 2023-11-02
    */
    @ApiOperation(value = "按id删除用户信息",notes = "按id删除用户信息")
    @PostMapping(value = "/delete")
    public ResultEntity delete(@RequestParam Serializable id) {
        userService.removeById(id);
        return ResultEntity.success();
    }


    /**
    * 根据id查询用户信息
    *
    * @author song
    * @Date 2023-11-02
    */
    @SentinelResource(
        value = "detail",
        blockHandlerClass = SentinelExceptionHandler.class,
        blockHandler = "handle"
    )
    @ApiOperation(value = "根据id查询用户信息",notes = "根据id查询修改用户信息")
    @GetMapping(value = "/detail")
    public ResultEntity<User> detail(@RequestParam Serializable id) {
        User user = userService.getById(id);
        return ResultEntity.success(user);
    }

    /**
     * 用户登录
     * @param loginParam
     * @return
     */
    @SentinelResource(
            value = "login",
            blockHandlerClass = SentinelBlockHandler.class,
            blockHandler = "blockHandler"
    )
    @ApiOperation(value = "用户登录",notes = "用户登录")
    @PostMapping(value = "/login")
    public ResultEntity login(@RequestBody LoginParam loginParam){
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getUsername, loginParam.getUsername());
        User user = userService.getOne(lambda);
        if (user == null){
            return ResultEntity.failMessage("用户不存在！");
        }
        if (!loginParam.getPassword().equals(user.getPassword())){
            return ResultEntity.failMessage("密码错误！");
        }
        String token = JwtUtil.sign(loginParam.getUsername());
        redisTemplate.opsForHash().put(RedisConstants.LOGIN_USER_KEY, token, JSONObject.toJSONString(user));
        return ResultEntity.successDataMessage(token, "登陆成功！");
    }

    @ApiOperation(value = "订单编号查订单",notes = "订单编号查订单")
    @GetMapping("/order/query")
    public ResultEntity queryOrderByNum(
            @RequestParam String num
    ){
        return orderService.getByNum(num);
    }
}